<template>
  <el-dialog
    title="系统设置"
    :visible.sync="dialogVisible"
    :close-on-click-modal="!isInitialSetup"
    :close-on-press-escape="!isInitialSetup"
    :show-close="!isInitialSetup"
    width="1000px"
    append-to-body
    custom-class="warm-dialog system-settings-dialog"
    @close="handleClose"
  >
    <el-tabs v-model="activeTab">
      <!-- 基本设置 Tab -->
      <el-tab-pane label="基本设置" name="basic">
        <el-form ref="settingsForm" :model="settings" :rules="settingsRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="系统标题" prop="sysTitle">
                <el-input v-model="settings.sysTitle" placeholder="请输入系统标题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司名称" prop="cmpName">
                <el-input v-model="settings.cmpName" placeholder="请输入公司名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系电话" prop="customerPhone">
                <el-input
                  v-model.trim="settings.customerPhone"
                  placeholder="请输入联系电话"
                  clearable
                  @input="handlePhoneInput"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系邮箱" prop="customerEmail">
                <el-input
                  v-model.trim="settings.customerEmail"
                  placeholder="请输入联系邮箱"
                  clearable
                  @input="handleEmailInput"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="系统Logo" prop="sysLogo">
                <image-upload v-model="settings.sysLogo" :limit="1" :multiple="false"/>
                <div class="form-tip">建议上传正方形图片，大小不超过2MB</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="标题Logo" prop="titleLogo">
                <image-upload v-model="settings.titleLogo" :limit="1" :multiple="false"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 功能设置 Tab -->
      <el-tab-pane label="功能设置" name="function">
        <el-form ref="functionForm" :model="settings" :rules="settingsRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="打卡功能">
                <el-switch
                  v-model="settings.sysCheak"
                  active-value="1"
                  inactive-value="0"
                  active-color="#0d4ca4"
                  inactive-color="#dcdfe6"
                />
                <span class="switch-label">{{ settings.sysCheak === '1' ? '开启' : '关闭' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="短信提醒">
                <el-switch
                  v-model="settings.message"
                  active-value="1"
                  inactive-value="0"
                  active-color="#0d4ca4"
                  inactive-color="#dcdfe6"
                />
                <span class="switch-label">{{ settings.message === '1' ? '开启' : '关闭' }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="无居住判定" prop="noOpen">
                <el-input-number
                  v-model="settings.noOpen"
                  :min="1"
                  :max="365"
                  :step="1"
                  controls-position="right"
                />
                <span class="input-suffix">天不开门视为无居住</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="钥匙到期提醒" prop="keyDate">
                <el-input-number
                  v-model="settings.keyDate"
                  :min="1"
                  :max="365"
                  :step="1"
                  controls-position="right"
                />
                <span class="input-suffix">天前提醒钥匙到期</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer" class="dialog-footer">
      <el-button v-if="!isInitialSetup" @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSave">{{ isInitialSetup ? '确认设置' : '保 存' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { formatOssUrl } from "@/utils/ossUtils";
import ImageUpload from "@/components/ImageUpload";

export default {
  name: 'SystemSettings',
  components: {
    ImageUpload
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    initialSettings: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      activeTab: 'basic',
      settings: {
        customerPhone: '',
        customerEmail: '',
        ...this.initialSettings
      },
      isInitialSetup: false,
      settingsRules: {
        sysTitle: [
          { required: true, message: "系统标题不能为空", trigger: "blur" }
        ],
        cmpName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        customerPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: ["blur", "change"] }
        ],
        customerEmail: [
          { required: true, message: "联系邮箱不能为空", trigger: "blur" },
          { type: 'email', message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ],
        noOpen: [
          { required: true, message: "天数不能为空", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "请输入数字", trigger: "blur" }
        ],
        keyDate: [
          { required: true, message: "钥匙到期提醒天数不能为空", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "请输入数字", trigger: "blur" }
        ]
      },
      originalSettings: {}
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initSettings();
      }
    },
    initialSettings: {
      handler(val) {
        this.initSettings();
        // 如果没有 id，说明是初始设置
        this.isInitialSetup = !val.id;
      },
      immediate: true
    }
  },
  methods: {
    initSettings() {
      // 保存初始值，用于取消时恢复
      this.originalSettings = JSON.parse(JSON.stringify(this.initialSettings));

      const defaultSettings = {
        deptId: 0,
        sysTitle: "校园智能门锁管理系统",
        sysLogo: "",
        titleLogo: "",
        sysCheak: "1",
        message: "1",
        noOpen: "30",
        keyDate: "7",
        cmpName: "",
        customerPhone: "",
        customerEmail: ""
      };

      // 先设置默认值
      this.settings = { ...defaultSettings };

      // 然后用初始值覆盖默认值
      if (this.initialSettings) {
        Object.keys(this.initialSettings).forEach(key => {
          if (this.initialSettings[key] !== undefined && this.initialSettings[key] !== null) {
            this.settings[key] = this.initialSettings[key];
          }
        });
      }
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit('close');
    },
    handleCancel() {
      if (this.isInitialSetup) {
        this.$message.warning('请完成初始系统设置');
        return;
      }
      this.dialogVisible = false;
    },
    handleSave() {
      console.log('开始保存设置...');
      console.log('当前设置数据:', this.settings);

      // 先验证基本设置表单
      this.$refs.settingsForm.validate((valid1) => {
        if (!valid1) {
          console.log('基本设置验证失败');
          return false;
        }

        // 如果当前在功能设置tab，也验证功能设置表单
        if (this.activeTab === 'function') {
          this.$refs.functionForm.validate((valid2) => {
            if (!valid2) {
              console.log('功能设置验证失败');
              return false;
            }
            this.submitSettings();
          });
        } else {
          this.submitSettings();
        }
      });
    },
    submitSettings() {
      try {
        console.log('提交设置数据...');
        const saveData = {
          ...this.settings,
          deptId: this.settings.deptId || this.initialSettings.deptId || 0
        };
        console.log('提交的数据:', saveData);
        this.$emit('save', saveData);
        this.dialogVisible = false;
      } catch (error) {
        console.error('保存设置时出错:', error);
        this.$message.error('保存设置失败，请重试');
      }
    },
    beforeLogoUpload(file) {
      const isImage = file.type.indexOf("image/") !== -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    handleSysLogoUpload({ file }) {
      const formData = new FormData();
      formData.append('file', file);

      this.$http.post('/api/common/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.settings.sysLogo = formatOssUrl(response.data.url);
          this.$message.success("系统Logo上传成功");
        } else {
          this.$message.error(response.data.msg || '上传失败');
        }
      }).catch(error => {
        console.error('上传失败:', error);
        this.$message.error('上传失败，请重试');
      });
    },
    handleTitleLogoUpload({ file }) {
      const formData = new FormData();
      formData.append('file', file);

      this.$http.post('/api/common/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.settings.titleLogo = formatOssUrl(response.data.url);
          this.$message.success("标题Logo上传成功");
        } else {
          this.$message.error(response.data.msg || '上传失败');
        }
      }).catch(error => {
        console.error('上传失败:', error);
        this.$message.error('上传失败，请重试');
      });
    },
    handlePhoneInput(value) {
      // 移除非数字字符
      this.settings.customerPhone = value.replace(/\D/g, '').slice(0, 11);
    },
    handleEmailInput(value) {
      // 允许输入邮箱地址的有效字符
      this.settings.customerEmail = value.trim();
    }
  }
}
</script>

<style lang="scss" scoped>
/* 系统设置对话框样式 */
::v-deep .warm-dialog {
  border-radius: 12px;
  overflow: hidden;

  .el-dialog__header {
    background-color: #0d4ca4;
    padding: 16px 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .el-dialog__title {
      color: #ffffff;
      font-weight: 600;
      font-size: 18px;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: rgba(255, 255, 255, 0.9);

      &:hover {
        color: #ffffff;
      }
    }
  }

  .el-dialog__body {
    padding: 25px 25px 10px;
  }

  .el-dialog__footer {
    padding: 15px 20px 20px;
    text-align: right;

    .el-button--primary {
      background: linear-gradient(135deg, #1a56b0, #0d4ca4);
      border: none;
      border-radius: 8px;
      padding: 10px 20px;
      font-weight: 500;
      box-shadow: 0 3px 8px rgba(13, 76, 164, 0.3);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 12px rgba(13, 76, 164, 0.4);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

/* Tab 相关样式 */
::v-deep .el-tabs__nav-wrap {
  padding: 0 20px;

  &::after {
    height: 1px;
    background-color: #e8e8e8;
  }
}

::v-deep .el-tabs__item {
  font-size: 15px;
  height: 40px;
  line-height: 40px;

  &.is-active {
    color: #0d4ca4;
    font-weight: 600;
  }
}

::v-deep .el-tabs__active-bar {
  background-color: #0d4ca4;
  height: 3px;
  border-radius: 1.5px;
}

.form-tip {
  font-size: 12px;
  color: #5a7baf;
  margin-top: 5px;
}

.switch-label {
  margin-left: 10px;
  font-size: 14px;
  color: #333;
}

.input-suffix {
  margin-left: 10px;
  font-size: 14px;
  color: #333;
}

/* 针对系统设置表单样式的优化 */
::v-deep .system-settings-dialog {
  .el-form-item__label {
    color: #0d4ca4;
    font-weight: 500;
  }

  .el-input__inner {
    border-radius: 8px;
    border-color: #a0b8df;
    transition: all 0.3s;

    &:hover {
      border-color: #1a56b0;
    }

    &:focus {
      border-color: #0d4ca4;
      box-shadow: 0 0 0 2px rgba(13, 76, 164, 0.1);
    }
  }

  .el-input-number {
    width: 120px;
  }

  .el-switch__core {
    height: 22px;
    border-radius: 11px;
    width: 44px !important;
  }

  .el-switch.is-checked .el-switch__core::after {
    margin-left: 22px;
  }

  .el-switch__core::after {
    width: 18px;
    height: 18px;
    top: 1px;
    left: 1px;
    transition: all 0.3s;
  }
}
</style>

